package cc.comac.mom.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cc.comac.mom.api.EquipDevService;
import cc.comac.mom.bean.EquipDev;
import cc.comac.mom.bean.EquipDevBean;
import cc.comac.mom.bean.ImportReultData;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.datahandlers.entity.EquipCheckDetailDataHandler;
import cc.comac.mom.datahandlers.entity.EquipDevCategoryDataHandler;
import cc.comac.mom.datahandlers.entity.EquipDevDataHandler;
import cc.comac.mom.entity.EquipCheckDetailEntity;
import cc.comac.mom.entity.EquipDevCategoryEntity;
import cc.comac.mom.entity.EquipDevEntity;
import cc.comac.mom.util.ExcelUploadUtil;
import cc.comac.mom.util.ExportExcel;
import cc.comac.mom.util.ResultBean;
import cc.comac.mom.util.TimeUtil;

@Service
@RestController
public class EquipDevServiceImpl implements EquipDevService {

	@Autowired
	private EquipDevDataHandler equipDevDataHandler;
	@Autowired
	private EquipCheckDetailDataHandler equipCheckDetailDataHandler;

	@Autowired
	private EquipDevCategoryDataHandler equipDevCategoryDataHandler;
	@Override
	public ResultBean save(@RequestBody EquipDev obj) {
		// TODO Auto-generated method stub
		return equipDevDataHandler.save(obj);
	}

	@Override
	public ResultBean update(@RequestBody EquipDev obj) {
		// TODO Auto-generated method stub
		return equipDevDataHandler.update(obj);
	}

	@Override
	public ResultBean delete(@RequestBody EquipDev obj) {
		ResultBean resultBean = new ResultBean(true);
		EquipDev equipDev = equipDevDataHandler.getById(obj.getInnerData().getId());
		if (equipDev == null) {
			resultBean.setSuccess(false);
			resultBean.setMessage("数据不存在");
			return resultBean;
		}
		QueryWrapper<EquipCheckDetailEntity> queryWrapper = new QueryWrapper<EquipCheckDetailEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("dev_id", equipDev.getInnerData().getId());
		List<EquipCheckDetailEntity> list = equipCheckDetailDataHandler.list(queryWrapper);
		if (list != null && list.size() > 0) {
			resultBean.setSuccess(false);
			resultBean.setMessage("设备" + equipDev.getInnerData().getDevName() + " 被设备盘点引用，不可删除");
			return resultBean;
		}
		return equipDevDataHandler.delete(obj);
	}

	@Override
	public EquipDev getById(@RequestBody EquipDev obj) {
		// TODO Auto-generated method stub
		return equipDevDataHandler.getById(obj.getInnerData().getId());
	}

	@Override
	public ResultBean selectByCondition(@RequestBody EquipDev obj) {
		ResultBean resultBean = new ResultBean(true);
		EquipDevBean selectByCondition = equipDevDataHandler.selectByCondition(obj);
		resultBean.setObject(selectByCondition);
		return resultBean;
	}

	@Override
	public ResultBean select(@RequestBody EquipDevBean obj) {
		ResultBean resultBean = new ResultBean(true);
		List<EquipDevBean> selectByCondition = equipDevDataHandler.select(obj);
		resultBean.setObject(selectByCondition);
		return resultBean;
	}

	@Override
	public ResultBean selectAllData() {
		ResultBean resultBean = new ResultBean(true);
		ResultDev selectAllData = equipDevDataHandler.selectAllData();
		resultBean.setObject(selectAllData);
		return resultBean;
	}

	public ResultBean importEquipDev(@RequestPart("file") MultipartFile file, @RequestParam String rootPath)
			throws RuntimeException, IOException {
		ResultBean resultBean = new ResultBean(true);
//		if (file == null || file.isEmpty()) {
//			resultBean.setSuccess(false);
//			resultBean.setMessage("上传失败，请重新上传！");
//			return resultBean;
//		} else if (file.getSize() > 10000000) {
//			resultBean.setSuccess(false);
//			resultBean.setMessage("上传失败，文件大小不能超过10M!！");
//			return resultBean;
//		}
//
//		String fileName = file.getOriginalFilename();
//		File dir = new File(rootPath);
//		if (!dir.exists()) {
//			dir.mkdir();
//		}
//		File chunkFile = new File(dir, fileName);
//		try {
//			chunkFile.createNewFile();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		file.transferTo(chunkFile);

		// 已存在设备编号
		ArrayList<String> listDevNumber = new ArrayList<String>();
		// 已存在的设备类型编号
		HashMap<String, Long> mapDevType = new HashMap<String, Long>();
		// 重复的集合
		ArrayList<Object> errorList = new ArrayList<Object>();
		// 新增的数据集合
		ArrayList<EquipDevEntity> listEntity = new ArrayList<EquipDevEntity>();
		// 查询数据库存在的设备编号，添加到已存在的数据集合里
		QueryWrapper<EquipDevEntity> queryWrapper = new QueryWrapper<EquipDevEntity>();
		queryWrapper.eq("row_status", 1);
		List<EquipDevEntity> listEquipDevEntity = equipDevDataHandler.list(queryWrapper);
		if (listEquipDevEntity != null && listEquipDevEntity.size() > 0) {
			for (EquipDevEntity item : listEquipDevEntity) {
				listDevNumber.add(item.getDevNumber());
			}
		}
		// 查询已存在的设备类型
		QueryWrapper<EquipDevCategoryEntity> queryWrapper2 = new QueryWrapper<EquipDevCategoryEntity>();
		queryWrapper2.eq("row_status", 1);
		List<EquipDevCategoryEntity> list = equipDevCategoryDataHandler.list(queryWrapper2);
		if (list != null && list.size() > 0) {
			for (EquipDevCategoryEntity item : list) {
				mapDevType.put(item.getDevCategoryName(), item.getId());
			}
		}
		try {
			// FileInputStream in = new FileInputStream(file);
//			FileInputStream in = new FileInputStream(chunkFile);
			Workbook workbook;
			workbook = ExcelUploadUtil.getWorkBook(file);
			// Sheet的数量
			int sheetCount = workbook.getNumberOfSheets();
			// 循环sheet
			for (int i = 0; i < sheetCount; i++) {
				Sheet sheetAt = workbook.getSheetAt(i);
				// 行数
				int rowCount = sheetAt.getLastRowNum();
				System.out.println(rowCount + "行数");
				// 跳过第一行
				if (rowCount < 1) {
					continue;
				}
				// 循环行
				for (int j = 1; j <= rowCount; j++) {
					Row row = sheetAt.getRow(j);
					int cellCount = row.getPhysicalNumberOfCells();
					System.out.println(cellCount + "列数");
					Cell cell0 = row.getCell(0);
					Object devNumber = ExcelUploadUtil.getValue(cell0);
					String devNum= "";
					if (listEquipDevEntity.size() > 0) {
						for (EquipDevEntity equipDevEntity : listEquipDevEntity) {
							if (StringUtils.isEmpty(devNumber.toString())
									|| equipDevEntity.getDevNumber().equals(devNumber)) {
								ArrayList<Object> arrayList = new ArrayList<Object>();
								for (Cell cell : row) {
									arrayList.add(ExcelUploadUtil.getValue(cell));
								}
								arrayList.add("设备编号"+devNumber+"重复");
								devNum = devNumber.toString();
								errorList.add(arrayList);
								break;
							}
						}
					}
					// 数据为空
					if (devNumber == null || StringUtils.isNotEmpty(devNum)) {
						continue;
					}
					// 数据已存在
//					if (listDevNumber.contains(devNumber)) {
//						// 设备编号已经存在
//						continue;
//					}
					Object devName = ExcelUploadUtil.getValue(row.getCell(1));
					Object devModel = ExcelUploadUtil.getValue(row.getCell(2));
					// 设备类型编号
					Object devTypeNumber = ExcelUploadUtil.getValue(row.getCell(3));
					if (devTypeNumber == null) {
						continue;
					}
					if (mapDevType.get(devTypeNumber) == null || mapDevType.get(devTypeNumber) == 0) {
						// 设备类型不存在
						continue;
					}

					Object devUnit = ExcelUploadUtil.getValue(row.getCell(4));
					Object supplierName = ExcelUploadUtil.getValue(row.getCell(5));
					Object propertyType = ExcelUploadUtil.getValue(row.getCell(6));
					Object propertyStatus = ExcelUploadUtil.getValue(row.getCell(7));
					System.out.println(row.getCell(8).getCellTypeEnum().name());
					System.out.println(row.getCell(8).getCellTypeEnum());
//					if (row.getCell(8) != null) {
//						// 不是时间格式的
//						continue;
//					}
					Object productionDate = ExcelUploadUtil.getValue(row.getCell(8));
					Object devRemark = ExcelUploadUtil.getValue(row.getCell(9));
					Object devStatus = ExcelUploadUtil.getValue(row.getCell(10));
					Object userDepartment = ExcelUploadUtil.getValue(row.getCell(11));
					Object workShop = ExcelUploadUtil.getValue(row.getCell(12));
					Object location = ExcelUploadUtil.getValue(row.getCell(13));
					Object maintenanceTeam = ExcelUploadUtil.getValue(row.getCell(14));
					Object resDepartmentGroup = ExcelUploadUtil.getValue(row.getCell(15));
					Object resDepartmentLeader = ExcelUploadUtil.getValue(row.getCell(16));
					Object resDepartmentPerson = ExcelUploadUtil.getValue(row.getCell(17));
					Object assessment = ExcelUploadUtil.getValue(row.getCell(18));
					Object assessmentCycle = ExcelUploadUtil.getValue(row.getCell(19));
					Object resultStatus = ExcelUploadUtil.getValue(row.getCell(20));
//					if (row.getCell(21) != null && !"NUMERIC".equals(row.getCell(21).getCellTypeEnum().name())) {
//						// 不是时间格式的
//						continue;
//					}
					Object expiryDate = ExcelUploadUtil.getValue(row.getCell(21));

//					if (row.getCell(22) != null && !"NUMERIC".equals(row.getCell(22).getCellTypeEnum().name())) {
//						// 不是时间格式的
//						continue;
//					}
					Object inventoryDate = ExcelUploadUtil.getValue(row.getCell(22));

					EquipDevEntity equipDevEntity = new EquipDevEntity();
					equipDevEntity.setDevNumber(devNumber.toString());
					if (devName != null) {
						equipDevEntity.setDevName(devName.toString());
					}
					if (devModel != null) {
						equipDevEntity.setDevModel(devModel.toString());
					}
					equipDevEntity.setDevCategoryId(mapDevType.get(devTypeNumber));
					if (devUnit != null) {
						equipDevEntity.setDevUnit(devUnit.toString());
					}
					if (supplierName != null) {
						equipDevEntity.setSupplierName(supplierName.toString());
					}
					if (propertyType != null) {
						equipDevEntity.setPropertyType(propertyType.toString());
					}
					if (propertyStatus != null) {
						equipDevEntity.setPropertyStatus(propertyStatus.toString());
					}
					if (productionDate != null) {
						try {
							 String productionDateString = productionDate.toString();
							Date fomatLocalDateTimeToDate = TimeUtil.stringToDaye(productionDateString);
							equipDevEntity.setProductionDate(fomatLocalDateTimeToDate);
						} catch (RuntimeException e) {
							ArrayList<Object> arrayList = new ArrayList<Object>();
							for (Cell cell : row) {
								arrayList.add(ExcelUploadUtil.getValue(cell));
							}
							arrayList.add("时间" + productionDate + "格式有误，无法转化");
							errorList.add(arrayList);
							continue;
						}
						
					}
					if (devRemark != null) {
						equipDevEntity.setDevRemark(devRemark.toString());
					}

					if (devStatus != null) {
						equipDevEntity.setDevStatus(devStatus.toString());
					}
					if (userDepartment != null) {
						equipDevEntity.setUserDepartment(userDepartment.toString());
					}
					if (workShop != null) {
						equipDevEntity.setWorkShop(workShop.toString());
					}
					if (location != null) {
						equipDevEntity.setLocation(location.toString());
					}
					if (maintenanceTeam != null) {
						equipDevEntity.setMaintenanceTeam(maintenanceTeam.toString());
					}
					if (resDepartmentGroup != null) {
						equipDevEntity.setResDepartmentGroup(resDepartmentGroup.toString());
					}
					if (resDepartmentLeader != null) {
						equipDevEntity.setResDepartmentLeader(resDepartmentLeader.toString());
					}
					if (resDepartmentPerson != null) {
						equipDevEntity.setResDepartmentPerson(resDepartmentPerson.toString());
					}
					if (assessment != null) {
						if (assessment.equals("是")) {
							equipDevEntity.setAssessment(1);
						} else {
							equipDevEntity.setAssessment(2);
						}
						
					}
					if (assessmentCycle != null) {
						equipDevEntity.setAssessmentCycle(assessmentCycle.toString());
					}
					if (resultStatus != null) {
						if (resultStatus.equals("是")) {
							equipDevEntity.setResultStatus(1);
						} else {
							equipDevEntity.setResultStatus(0);
						}
						
					}
					if (expiryDate != null) {
						try {
							
							Date fomatLocalDateTimeToDate = TimeUtil.stringToDaye(expiryDate.toString());
							equipDevEntity.setExpiryDate(fomatLocalDateTimeToDate);
						} catch (RuntimeException e) {
							ArrayList<Object> arrayList = new ArrayList<Object>();
							for (Cell cell : row) {
								arrayList.add(ExcelUploadUtil.getValue(cell));
							}
							arrayList.add("时间" + expiryDate + "格式有误，无法转化");
							errorList.add(arrayList);
							continue;
						}

					}
					if (inventoryDate != null) {
						try {
//							DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//							LocalDateTime parseTime = LocalDateTime.parse(productionDate.toString(), df);
							Date fomatLocalDateTimeToDate = TimeUtil.stringToDaye(inventoryDate.toString());
							equipDevEntity.setInventoryDate(fomatLocalDateTimeToDate);
						} catch (RuntimeException e) {
							ArrayList<Object> arrayList = new ArrayList<Object>();
							for (Cell cell : row) {
								arrayList.add(ExcelUploadUtil.getValue(cell));
							}
							arrayList.add("时间" + inventoryDate + "格式有误，无法转化");
							errorList.add(arrayList);
							continue;
						}

					}
					listEntity.add(equipDevEntity);
					listDevNumber.add(devNumber.toString());
				}
			}
//			chunkFile.delete();
			if (listEntity.size() > 0) {
				equipDevDataHandler.importBatch(listEntity);
			}
			ImportReultData importReultData = new ImportReultData();
			importReultData.setErrorList(errorList);
			importReultData.setSuccessRow(listEntity.size());
			importReultData.setErrorRow(errorList.size());
			importReultData.setTotalRow(listEntity.size() + errorList.size());
			resultBean.setObject(importReultData);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		chunkFile.delete();
		return resultBean;
	}

	@Override
	public String exportData(HttpServletRequest request, HttpServletResponse response, @RequestBody EquipDevBean obj) {
		List<EquipDevBean> list = equipDevDataHandler.exportSelectByCondition(obj);
		String[] rowsName = new String[] { "设备编号", "设备名称", "规格型号", "设备类型", "计量单位", "品牌商", "资产类别", "资产状态", "入账日期", "备注",
				"设备状态", "使用部位", "所在位置", "具体位置", "维修组", "使用部门班组", "使用部门领导", "使用责任人", "是否考核", "考核周期", "完好状态", "完好有效期",
				"盘点日期", "创建人", "创建时间", "修改人", "修改时间", "预留" };
		List<Object[]> dataList = new ArrayList<Object[]>();
		for (int i = 0; i < list.size(); i++) {
			Object[] objs = new Object[rowsName.length];//
			EquipDevBean devBean = list.get(i);
			objs[0] = devBean.getDevNumber();
			objs[1] = devBean.getDevName();
			objs[2] = devBean.getDevModel();
			objs[3] = devBean.getDevDategoryName();
			objs[4] = devBean.getDevUnitBean();
			objs[5] = devBean.getSupplierName();
			objs[6] = devBean.getPropertyType();
			objs[7] = devBean.getPropertyStatusBean();
			objs[8] = devBean.getProductionDate();
			objs[9] = devBean.getDevRemark();
			objs[10] = devBean.getDevStatusBean();
			objs[11] = devBean.getUserDepartment();
			objs[12] = devBean.getWorkShopBean();
			objs[13] = devBean.getLocation();
			objs[14] = devBean.getMaintenanceTeam();
			objs[15] = devBean.getResDepartmentGroup();
			objs[16] = devBean.getResDepartmentLeader();
			objs[17] = devBean.getResDepartmentPerson();
			if (devBean.getAssessment() == 1) {
				objs[18] = "是";
			} else {
				objs[18] = "否";
			}

			objs[19] = devBean.getAssessmentCycle();

			if (devBean.getResultStatus() == 1) {
				objs[20] = "是";
			} else {
				objs[20] = "否";
			}

			objs[21] = devBean.getExpiryDate();
			objs[22] = devBean.getInventoryDate();

			objs[23] = devBean.getCreator();
			objs[24] = devBean.getCreationTime();
			objs[25] = devBean.getLastModifier();
			objs[26] = devBean.getLastModifiedTime();
			objs[27] = "";
			dataList.add(objs);
		}

		String fileName = "设备主数据";
		// 执行导出
		String filePath = ExportExcel.exportExcel(request, response, fileName, rowsName, dataList,
				"yyyy-MM-dd HH:mm:ss");
		return filePath;
	}

}
